package com.eurasia.assignment.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.eurasia.assignment.domain.User;
import com.eurasia.assignment.service.UserService;

@RestController
@RequestMapping("/users")
public class UserController {

    private final UserService userService;

    public UserController(UserService userService) {
        this.userService = userService;
    }

    /**
     * 获取学生列表，支持通过真实姓名过滤
     * @param realName 真实姓名(可选)，支持模糊匹配
     * @return 学生列表
     */
    @GetMapping("/students")
    public ResponseEntity<Map<String, Object>> getStudents(
            @RequestParam(required = false, defaultValue = "") String realName) {
        List<User> students = userService.findStudentsByRealName(realName);
        
        // 过滤敏感信息
        List<Map<String, Object>> studentDTOs = students.stream().map(student -> {
            Map<String, Object> studentDTO = new HashMap<>();
            studentDTO.put("id", student.getId());
            studentDTO.put("username", student.getUsername());
            studentDTO.put("email", student.getEmail());
            studentDTO.put("realName", student.getRealName());
            studentDTO.put("enabled", student.isEnabled());
            return studentDTO;
        }).collect(Collectors.toList());
        
        Map<String, Object> response = new HashMap<>();
        response.put("students", studentDTOs);
        response.put("total", studentDTOs.size());
        
        return ResponseEntity.ok(response);
    }

    /**
     * 获取所有用户列表
     * 只有管理员角色才能访问此接口
     * @return 用户列表，不包含敏感信息如密码
     */
    @GetMapping("/list")
    @PreAuthorize("hasAuthority('ROLE_ADMIN')")
    public ResponseEntity<?> getAllUsers() {
        List<User> users = userService.findAllUsers();
        
        // 过滤敏感信息
        List<Map<String, Object>> userDTOs = users.stream().map(user -> {
            Map<String, Object> userDTO = new HashMap<>();
            userDTO.put("id", user.getId());
            userDTO.put("username", user.getUsername());
            userDTO.put("email", user.getEmail());
            userDTO.put("realName", user.getRealName());
            userDTO.put("enabled", user.isEnabled());
            userDTO.put("role", user.getRole());
            return userDTO;
        }).collect(Collectors.toList());
        
        Map<String, Object> response = new HashMap<>();
        response.put("users", userDTOs);
        response.put("total", userDTOs.size());
        
        return ResponseEntity.ok(response);
    }
    
    /**
     * 删除指定ID的用户
     * 只有管理员角色才能访问此接口
     * @param userId 要删除的用户ID
     * @return 删除成功返回204 No Content，用户不存在返回404 Not Found
     */
    @DeleteMapping("/{userId}")
    @PreAuthorize("hasAuthority('ROLE_ADMIN')")
    public ResponseEntity<?> deleteUser(@PathVariable Long userId) {
        boolean deleted = userService.deleteUser(userId);
        if (deleted) {
            Map<String, String> response = new HashMap<>();
            response.put("message", "用户删除成功");

            return ResponseEntity.ok(response);
        } else {
            Map<String, String> response = new HashMap<>();
            response.put("message", "用户不存在");
            return ResponseEntity.status(404).body(response);
        }
    }
}